/*
Copyright (c) 2014, Rick Wilson
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of 'Taareekah' nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package gameobject;

import gameobject.GOManager;
import gameobject.GOHandle;
import gameobject.Component;
import world.Terrain;
import world.GenericTerrainMap;
import world.World;
import world.BiomeType;
import world.BiomeMap;
import worldgeneration.WorldGenerator;
import util.Point;
import java.util.logging.Level;
import java.util.logging.Logger;

import parameters.*;
import java.util.logging.Level;
import java.util.logging.Logger;


import java.util.Set;
import java.util.HashSet;

public class InhabitedSite extends Component {
        private static final long serialVersionUID = 20140428L;
    
def popDensity(int pop) {
    return pop.toFloat().div(1024.0f);
}

    def getBiomeMod(int x, int y, BiomeMap map) {
        BiomeType type = map.getBiomeAtPoint(x, y);
        float ret = 0.0f;
        if (type.getName() == "grassland") {
            ret = 1500.0f;
        } else if (type.getName() == "coast" || type.getName() == "ocean") {
            ret = 750.0f;
        } else if (type.getName() == "swamp") {
            ret = 400.0f;
        } else if (type.getName() == "forest") {
            ret = 500.0f;
        } else {
            ret = 300.0f;
        }

        return ret;
    }
    
    def estimateCarryingCapacity(Point p, BiomeMap biome_map) {
        float avg_mod = 0.0f;
        float pop = (float)((int)getAttribute("fertile_population"));
        float workable_fields = pop.div(250.0f);
        if (pop > 1024.0f) {
            avg_mod += getBiomeMod(p.getX() - 1, p.getY() + 1, biome_map);
            avg_mod += getBiomeMod(p.getX(), p.getY() + 1, biome_map);
            avg_mod += getBiomeMod(p.getX() + 1, p.getY() + 1, biome_map);

            avg_mod += getBiomeMod(p.getX() - 1, p.getY(), biome_map);
            avg_mod += getBiomeMod(p.getX(), p.getY(), biome_map);
            avg_mod += getBiomeMod(p.getX() + 1, p.getY(), biome_map);

            avg_mod += getBiomeMod(p.getX() - 1, p.getY() - 1, biome_map);
            avg_mod += getBiomeMod(p.getX(), p.getY() - 1, biome_map);
            avg_mod += getBiomeMod(p.getX() + 1, p.getY() - 1, biome_map);

            avg_mod = avg_mod.div(9.0f);
        } else {
            avg_mod = getBiomeMod(p.getX(), p.getY(), biome_map);
        }

        float ret = workable_fields * avg_mod;
        

        return ret;
    }
    public InhabitedSite() {
        super();
        component_typename = "InhabitedSite";
        addAttribute("civilization", null);
        addAttribute("site_name", "");
        addAttribute("fertile_population", (int)0);
        addAttribute("child_population", (int)0);
        addAttribute("population", (int)0);
        addAttribute("location", null);
        addAttribute("deathrate", null);
        addAttribute("birthrate", null);
        setMethod("tickLog", this.&tickLog);
        setMethod("setLocation", this.&setLocation);
        addRequiredComponent("SimpleLocation");
        
    }
    
    public void setLocation(Point location) {
        setAttribute("location", location);
        getOwner().callMethod("SimpleLocation.move", location, location);
    }
    
    public int tickLog(BiomeMap biome_map) {
        float population = (float)((int)getAttribute("fertile_population"));
        float k = estimateCarryingCapacity((Point)getAttribute("location"), biome_map);
        float n_over_k = (population.div(k));
        float change = (float)getAttribute("birthrate") * population * (1.0f - n_over_k);
        
        int old_fertile_pop = (int)getAttribute("fertile_population");
        int old_child_pop = (int)getAttribute("child_population");
        
        int fertile_deaths = Math.round(calculateDeathRate() * (float)old_fertile_pop);
        int child_deaths = Math.round(calculateDeathRate() * (float)old_child_pop);
        int births = Math.round(change);
        
        int children_to_adults = Math.round((float)(old_child_pop - child_deaths) * 0.15f);
        
        int new_fertile_pop = old_fertile_pop + children_to_adults - fertile_deaths;
        if (new_fertile_pop < 0) {
            new_fertile_pop = 0;
        }
        int children = (int)getAttribute("child_population") + births - children_to_adults - child_deaths;
        
        setAttribute("fertile_population", new_fertile_pop);
        setAttribute("child_population", children);
        setAttribute("population", children + new_fertile_pop);
        
        return children + new_fertile_pop;
    }
    
    public int tick(float mod) {
        int old_fertile_pop = (int)getAttribute("fertile_population");
        int old_child_pop = (int)getAttribute("child_population");
        
        int fertile_deaths = Math.round(calculateDeathRate() * (float)old_fertile_pop);
        int child_deaths = Math.round(calculateDeathRate() * (float)old_child_pop);
        int births = Math.round(calculateBirthRate(mod) * (float)old_fertile_pop);
        
        int children_to_adults = Math.round((float)(old_child_pop - child_deaths) * 0.05f);
        
        int new_fertile_pop = old_fertile_pop + children_to_adults - fertile_deaths;
        if (new_fertile_pop < 0) {
            new_fertile_pop = 0;
        }
        int children = (int)getAttribute("child_population") + births - children_to_adults - child_deaths;
        
        setAttribute("fertile_population", new_fertile_pop);
        setAttribute("child_population", children);
        setAttribute("population", children + new_fertile_pop);
        return children + new_fertile_pop;
    }
    public float calculateDeathRate() {
        float base_rate = (float)getAttribute("deathrate");
        float density = popDensity((int)getAttribute("population"));
        if (density > 1.0f) {
            density = density.div(10.0f);
            base_rate = base_rate + (base_rate * density);
        }
        
        return base_rate;
    }
    public float calculateBirthRate(float mod) {
        return (float)getAttribute("birthrate") * mod;
    }
}